import { tools, ajax } from './ajax.js';

//#region 切换的部分
// querySelectorAll获取一组css选择器对应的元素
let switchSps = document.querySelectorAll(
  '.card .list-group-item:nth-child(1) span'
);

let items = document.querySelectorAll('.list-group-item');

console.log(switchSps, items);

function switchMode(mode) {
  if (mode == 1) {
    items[1].style.display = 'block';
    items[2].style.display = 'block';
    items[3].style.display = 'none';
    items[4].style.display = 'none';
  } else {
    items[1].style.display = 'none';
    items[2].style.display = 'none';
    items[3].style.display = 'block';
    items[4].style.display = 'block';
  }
}

switchMode(1);

switchSps[0].addEventListener('click', () => {
  switchMode(1);
});

switchSps[1].addEventListener('click', () => {
  switchMode(2);
});

//#endregion

//#region 邮箱登录的部分
let txt_email = document.getElementById('txt_email');
let txt_code = document.getElementById('txt_code');
let btnSendEmail = document.getElementById('btnSendEmail');
let btnLogin = document.getElementById('btnLogin');

btnSendEmail.addEventListener('click', () => {
  ajax.post(
    '/tool/sendEmailCode',
    {
      email: txt_email.value,
    },
    (data) => {
      showToast(data.message);
    }
  );
});

btnLogin.addEventListener('click', () => {
  ajax.post(
    '/user/auth/emailLogin',
    {
      email: txt_email.value,
      info: txt_code.value,
    },
    (data) => {
      if(data.success) {
        location.href = 'main.html'
        return;
      }
      showToast(data.message);
    }
  );
});

//#endregion

//#region 用户登录的部分
let txt_username = document.getElementById('txt_username');
let txt_password = document.getElementById('txt_password');
let btnULogin = document.getElementById('btnULogin');

btnULogin.addEventListener('click', () => {
  ajax.post(
    '/user/auth/login',
    {
      username: txt_username.value,
      password: tools.md5(txt_password.value),
    },
    (data) => {
      if(data.success) {
        location.href = 'main.html'
        return;
      }
      showToast(data.message);
    }
  );
});

//#endregion

//#region 弹出层提示框
let liveToast = document.getElementById('liveToast');
const toast = new bootstrap.Toast(liveToast);

const toastBody = document.querySelector('#liveToast .toast-body');

function showToast(message) {
  toastBody.innerHTML = message;
  toast.show();
}
//#endregion
